package com.example.anew.journey.mynewjourney.firstchangelogic.frstChangeSecondTimeCardiacDetection;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.example.anew.journey.mynewjourney.MyAnimationListener;
import com.example.anew.journey.mynewjourney.R;
import com.example.anew.journey.mynewjourney.customview.MyCardiacDetectionCustomView;
import com.example.anew.journey.mynewjourney.customview.MyVerticalScrollView;
import com.example.anew.journey.mynewjourney.customview.RingView;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeCardiacDetection.FirstChangeCardiacDetectionActivity;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeDirectionsUse.FirstChangeDirectionsUseActvity;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeHistoricalRecordDateList.FirstChangeHistoricalRecordDateListActivity;
import com.example.anew.journey.mynewjourney.firstchangelogic.frstChangeSecondTimeCardiacDetection.persenter.FrstChangeSecondTimeCardiacDetectionPersenter;
import com.example.anew.journey.mynewjourney.firstchangelogic.frstChangeSecondTimeCardiacDetection.view.ISFrstChangeSecondTimeCardiacDetectionView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jesse.nativelogger.NLogger;

/**
 * 杭州惟君医疗科技有限公司13
 * Created by 20433 on 2018/3/22
 * @deac  第二次测试 页面
 * @desc 东风山河绿，春已不折柳，繁花看不尽，处处惹人留
 * @desc 佛祖镇楼，bug辟容易
 */

public class FrstChangeSecondTimeCardiacDetectionActivity extends AppCompatActivity implements ISFrstChangeSecondTimeCardiacDetectionView {

    @Bind(R.id.activity_first_change_second_time_cariac_detection_mycardiac_detection_custom_view)
    MyCardiacDetectionCustomView activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_ringview)
    RingView activityFirstChangeSecondTimeCariacDetectionRingview;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_rl_jingu)
    RelativeLayout activityFirstChangeSecondTimeCariacDetectionRlJingu;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_tv_start_test)
    TextView activityFirstChangeSecondTimeCariacDetectionTvStartTest;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_iv_left_linkage)
    ImageView activityFirstChangeSecondTimeCariacDetectionIvLeftLinkage;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_tv_search_bt)
    TextView activityFirstChangeSecondTimeCariacDetectionTvSearchBt;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar)
    AppBarLayout appBar;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_recyclerview)
    RecyclerView activityFirstChangeSecondTimeCariacDetectionRecyclerview;
    @Bind(R.id.activity_first_change_second_time_cariac_detection_my_vertical_scroll_view)
    MyVerticalScrollView activityFirstChangeSecondTimeCariacDetectionMyVerticalScrollView;
    private ArrayList<Integer> mlist = new ArrayList<>();

    private FrstChangeSecondTimeCardiacDetectionPersenter mFrstChangeSecondTimeCardiacDetectionPersenter = new FrstChangeSecondTimeCardiacDetectionPersenter(this);
    private String SERVICES_UUID = "69400001-b5a3-f393-e0a9-e50e24dcca99";
    private String CHARECTERISTIC_UUID = "69400003-b5a3-f393-e0a9-e50e24dcca99";

    private String[] names = new String[1];
    private String devices_name;
    private boolean flag = true;
    private boolean flag_01 = true;
    private PopupWindow mSearchPopWindow;
    private ProgressBar progressBar;
    private ImageView iv_error;
    private TextView tv_search_state;
    private TextView tv_determine;
    private PopupWindow mDisconnectPopWindow;




    private BleDevice mbleDevice;
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private boolean Flag_02= false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_change_second_time_cariac_detection);
        ButterKnife.bind(this);
        mFrstChangeSecondTimeCardiacDetectionPersenter.initRecyclerView(activityFirstChangeSecondTimeCariacDetectionRecyclerview,this);
        mFrstChangeSecondTimeCardiacDetectionPersenter.PullUpJump(activityFirstChangeSecondTimeCariacDetectionMyVerticalScrollView);
        devices_name = getIntent().getStringExtra("devices_name");
        names[0] = "WelBi_"+devices_name;
      //  names[0] = "WelBi_3Y1K";
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setMaxConnectCount(7)
                .setOperateTimeout(5000);
      //  activityFirstChangeSecondTimeCariacDetectionRingview.startAnim();

    }

    // todo   /**=======================================================================*/
    @Override
    public void toTest() {
      //  checkPermissions(); //todo  开始扫描  ----> 1
        NLogger.e("TAG","====onScanning45========"+devices_name);
        Intent intent = new Intent(FrstChangeSecondTimeCardiacDetectionActivity.this, FirstChangeCardiacDetectionActivity.class); //FirstChangeCardiacDetectionActivity
        intent.putExtra("devices_name",devices_name);
        startActivity(intent);
    }
    @Override
    public void cancleTest() {
        if(mbleDevice != null){
            if (BleManager.getInstance().isConnected(mbleDevice)) {
                BleManager.getInstance().disconnect(mbleDevice); //TODO 断开连接
            }
        }else{
            BleManager.getInstance().cancelScan();  //todo 2 停止扫描  ----> 2
        }
//        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setFlag(true);
//        activityFirstChangeSecondTimeCariacDetectionRingview.setVisibility(View.GONE);
//        activityFirstChangeSecondTimeCariacDetectionRingview.stopAnim();
        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.stopAnim(0.5f);
        setStartTest("开始测试");

    }
    // todo
    private void setScanRule() {
        // todo 扫描的真正方法  --->5
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setServiceUuids(new UUID[]{UUID.fromString("69400001-b5a3-f393-e0a9-e50e24dcca99")})      // 只扫描指定的服务的设备，可选
                .setDeviceName(true)   // 只扫描指定广播名的设备，可选
                .setAutoConnect(false)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(2000)              // 扫描超时时间，可选，默认10秒
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }
    // todo 扫描的方法
    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                //todo 这里  提示进度----> 1
                Flag_02 = true;
                mFrstChangeSecondTimeCardiacDetectionPersenter.search();
                setStartTest("结束");
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);

            }

            @Override
            public void onScanning(BleDevice bleDevice) {
               // NLogger.e("TAG","====onScanning45========"+bleDevice.getName());
                if(bleDevice.getName().equals(names[0])){ //WelBi_0008
                    if (!BleManager.getInstance().isConnected(bleDevice)) {  // todo 判断设备是否连接
                        BleManager.getInstance().cancelScan();  //TODO 取消扫描
                        Flag_02 = false;
                        connect(bleDevice);
                    }
                }

            }
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                 //todo 这里  提示----> 2
                if(Flag_02){
                    mFrstChangeSecondTimeCardiacDetectionPersenter.failureSearch();
                    setStartTest("开始测试");
                }
                Flag_02 = false;
                //Toast.makeText(FrstChangeSecondTimeCardiacDetectionActivity.this,"设备扫描结束",Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleException exception) {  //todo 这里  结束提示进度----> 1
                mFrstChangeSecondTimeCardiacDetectionPersenter.failureSearch();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                mbleDevice = bleDevice;
                mFrstChangeSecondTimeCardiacDetectionPersenter.connectSuccess();
                getBluetoothGatt(bleDevice, gatt);  //todo 这里  结束提示进度----> 1
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                if(isActiveDisConnected){
                    Toast.makeText(FrstChangeSecondTimeCardiacDetectionActivity.this,"设备连接断开了",Toast.LENGTH_SHORT).show();
                }else{
                    mFrstChangeSecondTimeCardiacDetectionPersenter.Disconnect();
                    activityFirstChangeSecondTimeCariacDetectionRingview.setVisibility(View.GONE);
                    activityFirstChangeSecondTimeCariacDetectionRingview.stopAnim();
                    activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.stopAnim(0.5f);
                }
            }
        });
    }

    private void getBluetoothGatt(final BleDevice bleDevice, final BluetoothGatt gatt) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //todo 这里 逻辑处理-----获取特征值-------------------------->
                for (BluetoothGattService bluetoothGattService : gatt.getServices()) {
                    if(bluetoothGattService.getUuid().toString().equals("69400001-b5a3-f393-e0a9-e50e24dcca99")){
                        for (BluetoothGattCharacteristic bluetoothGattCharacteristic : bluetoothGattService.getCharacteristics()) {
                            int charaProp =   bluetoothGattCharacteristic.getProperties();
                            if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { // todo 判断是否是  Notify
                                //读取数据
                                MyNotify(bleDevice,bluetoothGattService.getUuid(),bluetoothGattCharacteristic.getUuid());
                            }
                        }
                    }
                }
            }
        }).start();

    }
    private void MyNotify(BleDevice bleDevice, UUID serviceuuid, UUID Characteristicuuid1) {
        //todo 打开通知
        BleManager.getInstance().notify(bleDevice,
                serviceuuid.toString(),
                Characteristicuuid1.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        myController();
//                         //todo 这里  停止动画
//                        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.startAnim(359);
//                        setStartTest("结束");
//                        mlist.clear();
                    }
                    @Override
                    public void onNotifyFailure(final BleException exception) {}
                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        String str = new String(data);
                        if(str.contains("7Ftl_")){  //
                            String[]  srr = str.split("_");
                            if(srr[1].contains("000")){
                                activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setUppertest("---bpm");
                            }else{
                                activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setUppertest(srr[1]+"bpm");
                             //   activityFirstChangeCardiacDetectionTvHeartRate.setText(srr[1]);
                               // mFrstChangeSecondTimeCardiacDetectionPersenter.TestReSult(srr[1],FrstChangeSecondTimeCardiacDetectionActivity.this);
                            }
                        }else if(str.contains("9StaFt_")) {
                            String[] srr = str.split("_");
                            int date = 0;
                            try {
                                 date = Integer.parseInt(srr[0].trim());
                                mlist.add(date);
                            } catch (NumberFormatException e) {

                            }finally {
                                if(mlist.size()> 3){
                                    int mytestDate =   mlist.get(0)+mlist.get(1)+mlist.get(2)+mlist.get(3);
                                    activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setUppertest(srr[1]+"bpm");
                                    mFrstChangeSecondTimeCardiacDetectionPersenter.TestReSult(srr[1], FrstChangeSecondTimeCardiacDetectionActivity.this);
                                }

                            }
                        }
                    }
                });
    }
    /*==============================**/
    // todo 权限申请----> 3
    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            setStartTest("开始测试");
            Toast.makeText(this, "请先打开蓝牙", Toast.LENGTH_LONG).show();
            activityFirstChangeSecondTimeCariacDetectionRingview.setVisibility(View.GONE);
            activityFirstChangeSecondTimeCariacDetectionRingview.stopAnim();
            return;
        }
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("当前手机扫描蓝牙需要打开定位功能")
                            .setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton("前往设置",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    setScanRule();
                    startScan(); //TODO 开始扫描 扫描的方法  ---->4
                }
                break;
        }
    }


    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
                setScanRule();
                startScan();
            }
        }
    }


   // todo  /**=======================================================================*/

    @OnClick({R.id.activity_first_change_second_time_cariac_detection_tv_start_test, R.id.activity_first_change_second_time_cariac_detection_iv_left_linkage,R.id.activity_first_change_second_time_cariac_detection_tv_search_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_first_change_second_time_cariac_detection_tv_start_test:
                mFrstChangeSecondTimeCardiacDetectionPersenter.onClickStartTest();
                break;
            case R.id.activity_first_change_second_time_cariac_detection_iv_left_linkage:
                finish();
                break;
            case R.id.activity_first_change_second_time_cariac_detection_tv_search_bt:
                mFrstChangeSecondTimeCardiacDetectionPersenter.onClickeTips();
                break;
        }
    }


    // TODO 获取焦点
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

    }
    // TODO 失去焦点  可以进行一些轻量级的存储数据和去初始化工作
    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleManager.getInstance().disconnectAllDevice(); //todo 释放一些资源
        BleManager.getInstance().destroy();
    }

    // 显示提示Toast信息
    @Override
    public void showToastInformation(String str) {
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }
    // 获取开始测试
    @Override
    public String getStartTest() {
        return activityFirstChangeSecondTimeCariacDetectionTvStartTest.getText().toString().trim();
    }
    //设置开始测试
    @Override
    public void setStartTest(String str) {
        activityFirstChangeSecondTimeCariacDetectionTvStartTest.setText(str);
    }
    // 跳转到小贴士页面
    @Override
    public void toTipsPager() {
        Intent intent = new Intent(FrstChangeSecondTimeCardiacDetectionActivity.this, FirstChangeDirectionsUseActvity.class);
        intent.putExtra("identification_code",1);
        startActivity(intent);
    }
    // 上画跳转到历史记录页面
    @Override
    public void toHistoricalRecord() {
        Intent intent = new Intent(FrstChangeSecondTimeCardiacDetectionActivity.this, FirstChangeHistoricalRecordDateListActivity.class);
        startActivity(intent);
    }




    private void myController() {
        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.startAnim(359);
      //  activityFirstChangeSecondTimeCariacDetectionRingview.setVisibility(View.VISIBLE);

        setStartTest("结束");
        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setFlag(false);
        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setmAnimationListener(new MyAnimationListener() {
            @Override
            public void onstart() {

            }

            @Override
            public void onCancel() {
               /* activityFirstChangeSecondTimeCariacDetectionRingview.setVisibility(View.GONE);
                // SetStartTest(0xffffffff, R.drawable.cardiac_detection_tvbg_selector_nomale,"开始检测");
                activityFirstChangeSecondTimeCariacDetectionRingview.stopAnim();
                activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.stopAnim(0.5f);
                setStartTest("开始测试");*/

            }

            @Override
            public void onRepeat() {

            }

            @Override
            public void onEnd() {
                activityFirstChangeSecondTimeCariacDetectionRingview.setVisibility(View.GONE);
                setStartTest("开始测试");
                activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.stopAnim(0.5f);

            }
        });
    }

    //显示搜素提示框
    @Override
    public void showSearch() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.blooth_search, null);
        mSearchPopWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mSearchPopWindow.setContentView(contentView);
        progressBar = contentView.findViewById(R.id.blooth_search_progressBar);
        iv_error = contentView.findViewById(R.id.blooth_search_iv_error);
        tv_search_state = contentView.findViewById(R.id.blooth_search_tv_search_state);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_first_change_second_time_cariac_detection, null);
        mSearchPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }

    @Override
    public void cancleSearch() {
        mSearchPopWindow.dismiss();
    }

    @Override
    public void failureSearch() {
        iv_error.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        tv_search_state.setText("连接失败");

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //mFrstChangeSecondTimeCardiacDetectionPersenter.search();
                setStartTest("开始测试");
                cancleSearch();
                cancleTest();

            }
        },1000);
    }

    //显示连接断开提示宽
    @Override
    public void showDisconnect() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.blooth_disconnect, null);
        mDisconnectPopWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mDisconnectPopWindow.setContentView(contentView);
        tv_determine = contentView.findViewById(R.id.blooth_disconnect_tv_determine);
        tv_determine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancleDisconnect();
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_first_change_second_time_cariac_detection, null);
        mDisconnectPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
    }

    @Override
    public void cancleDisconnect() {
        mDisconnectPopWindow.dismiss();
    }

    @Override
    public void connectSuccess() {
        iv_error.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
        tv_search_state.setText("连接成功");
        iv_error.setImageResource(R.mipmap.right_and_wrong);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //mFrstChangeSecondTimeCardiacDetectionPersenter.search();
                setStartTest("结束");
                cancleSearch();
            }
        },1000);
    }

    @Override
    public void findPager() {
        finish();
    }

    @Override
    public void setMycardiacDetectionDate(String str) {
        activityFirstChangeSecondTimeCariacDetectionMycardiacDetectionCustomView.setUppertest(str+" bpm");
    }

}
